<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');


require_once('tcms_sitemap_entry.class.php');


class TCMS_Sitemap_Entry_DBC extends TCMS_Sitemap_Entry implements I_DB_Storable {
	public function save(DB_Connection $dbc) {
		$ret = false;

		if ($this->get_id()) {
			$ret = $this->update($dbc);
		} else {
			$ret = $this->insert($dbc);
			$this->set_id($ret);
		}

		return $ret;
	}


	public function load_by_id(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);

		$ret = false;

		$sql = "select path, weight, change_freq from tcms_sitemap where id = $id";
		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();

			$this->set_id($id);
			$this->set_path(stripslashes($rez_obj->PATH));
			$this->set_weight($rez_obj->WEIGHT);
			$this->set_change_freq($rez_obj->CHANGE_FREQ);
			$ret = $id;
		}

		return $ret;
	}


	protected function insert(DB_Connection $dbc) {
		$ret = false;

		$id = $dbc->generate_id('tcms_sitemap_seq');
		$path = addslashes($this->get_path());
		$weight = $this->get_weight();
		$change_freq = $this->get_change_freq();

		if ($id) {
			$sql = "insert into tcms_sitemap (id, ".
									      "path, ".
									      "weight, ".
									      "change_freq ".
									      ") ".
								"values ".
									      "($id,".
									      "'$path', ".
									      "$weight, ".
									      "$change_freq ".
									      ")";
			$dbc->execute($sql);
			$ret = $id;
		} else {
			throw new TE_Exception('tcms_sitemap_seq');
		}

		return $ret;
	}


	protected function update(DB_Connection $dbc) {
		$id = $this->get_id();

		$path = addslashes($this->get_path());
		$weight = $this->get_weight();
		$change_freq = $this->get_change_freq();

		$sql = "update tcms_sitemap set ".
						"path = '$path', ".
						"weight = $weight, ".
						"change_freq = $change_freq ".
					"where id = ".$id;

		$dbc->execute($sql);
		$ret = $id;

		return $ret;
	}


	public static function delete(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);

		$sql = "delete from tcms_sitemap where id = $id";
		$dbc->execute($sql);
	}


	public static function get_sql_for_grid() {
		$sql = "select id, path, weight, change_freq from tcms_sitemap order by path asc";

		return $sql;
	}


	public static function	get_sql_count_for_grid() {
		$sql = "select count(id) as total_rows from tcms_sitemap";

		return $sql;
	}


	public static function is_unique_path(DB_Connection $dbc, $path, $id = 0) {
		tangra_if_not_int_throw_e($id);
		$path = addslashes($path);

		$sql = "select id from tcms_sitemap where id <> $id and path = '$path' ";
		$rez = $dbc->execute($sql);

		return $rez->is_eod();
	}


	public static function sql_get_entries_for_sitemap(DB_Connection $dbc) {
		$sql = "select path, weight, change_freq from tcms_sitemap";

		return $sql;
	}
}